package com.bit.cfdi.web.validators.login;

import org.zkoss.bind.ValidationContext;
import org.zkoss.bind.validator.AbstractValidator;

import com.bit.cfdi.web.constants.CFDIConstants;
import com.bit.cfdi.web.services.UsuarioService;

public class EmailRegisterValidation extends AbstractValidator {
	
	private UsuarioService usuarioService;
	
	private String emailFieldName;
	
	public EmailRegisterValidation(final String emailFieldName, 
			final UsuarioService usuarioService) {
		
		this.emailFieldName = emailFieldName;
		this.usuarioService = usuarioService;
	}

	@Override
	public void validate(final ValidationContext ctx) {
		String emailToValidate = (String) ctx.getProperties(emailFieldName)[0]
				.getValue();
		if(emailToValidate == null || emailToValidate.trim().isEmpty()) {
			return;
		}
		if(!emailToValidate.matches(CFDIConstants.EMAIL_PATTERN)) {
			addInvalidMessage(ctx, emailFieldName, "Email invalido");
			return;
		}
		if(usuarioService.getByEmail(emailToValidate)!=null) {
			addInvalidMessage(ctx, emailFieldName, 
					"Email registrado previamente");
			return;
		}
	}

}
